package com.thinksns.sociax.t4.android;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import com.thinksns.sociax.android.R;
import com.thinksns.sociax.api.Api;
import com.thinksns.sociax.component.CustomTitle;
import com.thinksns.sociax.component.LeftAndRightTitle;
import com.thinksns.sociax.constant.AppConstant;
import com.thinksns.sociax.photograph.gui.widgets.BottomBar;
import com.thinksns.sociax.photograph.utils.JLog;
import com.thinksns.sociax.t4.android.Listener.UnreadMessageListener;
import com.thinksns.sociax.t4.android.chat.OnChatListener;
import com.thinksns.sociax.t4.android.data.StaticInApp;
import com.thinksns.sociax.t4.android.fragment.FragmentHome;
import com.thinksns.sociax.t4.android.fragment.FragmentMessage;
import com.thinksns.sociax.t4.android.fragment.FragmentMy;
import com.thinksns.sociax.t4.android.fragment.FragmentSociax;
import com.thinksns.sociax.t4.android.img.Bimp;
import com.thinksns.sociax.t4.android.temp.SelectImageListener;
import com.thinksns.sociax.t4.android.video.PreferenceUtils;
import com.thinksns.sociax.t4.model.ModelNotification;
import com.thinksns.sociax.t4.sharesdk.ShareSDKManager;
import com.thinksns.sociax.t4.unit.UnitSociax;
import com.thinksns.sociax.thinksnsbase.exception.ApiException;
import com.thinksns.sociax.thinksnsbase.utils.Anim;
import com.thinksns.sociax.thinksnsbase.utils.PrefUtils;
import com.thinksns.tschat.chat.TSChatManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 类说明：app主页
 *
 * @author wz
 * @version 1.0
 * @date 2014-10-16
 */
public class ActivityHome extends ThinksnsAbscractActivity implements OnChatListener,
        UnreadMessageListener {

    public static final int GET_SOCKET_ADDRESS = 111;


    // 监听当前fragment
    private FragmentSociax currentFragment;
    private FragmentHome fg_home;
    private FragmentMessage fg_message;
    // my用到的变量
    private FragmentMy fg_my;

    // handler ,规定msg.arg1标记载入类型，msg.arg2标记操作对象
    private ActivityHandler handler;
    private final int SELECT = 201;// 标记handler执行的是载入页面
    //消息未读数
//    private BadgeView badgeMessage, badgeMy;

    private DoubleClickExitHelper mDoubleClickExit;

    private int unreadMsg = 0;

    private String skip_from;//从哪跳转来

    protected SelectImageListener listener_selectImage;   //拍照工具

    private BottomBar mBottomBar;

    private ModelNotification mdNotification;

    @Override
    @SuppressLint("MissingSuperCall")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreateNoTitle(savedInstanceState);
        // 其他activity尽量以这种格式进入页面：1.初始化intent；2.初始化UI；3.初始化Listener；4.初始化数据，创建时可直接复制com.zhishisoft.v4.android.uint-->activity
        initIntentData();
        initView();
        initListener();
        initData();
        //启动极光推送
        ShareSDKManager.register();
        getSocketAddress(); // 获取聊天 socket 地址，启动 socket 连接
        EventBus.getDefault().register(this);
    }

    /**
     * 初始化intent携带的信息
     */
    private void initIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            //进入主页的方式，比如来自通知栏
            skip_from = intent.getStringExtra("type");
        }
    }

    /**
     * 初始化页面
     */
    private void initView() {
        mDoubleClickExit = new DoubleClickExitHelper(this);
        mBottomBar = (BottomBar) findViewById(R.id.home_bottom_bar);

//        badgeMessage = (BadgeView) findViewById(R.id.badgeMessage);TODO
//        badgeMy = (BadgeView) findViewById(R.id.badgeMy);
        handler = new ActivityHandler();

        listener_selectImage = new SelectImageListener(this);

    }

    /**
     * 初始化监事件 暂时以new OnClickListener替代所有监听事件，后面考虑到代码优化只使用1个click即可
     */
    private void initListener() {
        JLog.i("initListener");
        mBottomBar.setBottomBarListener(new BottomBar.OnBottomBarListener() {
            @Override
            public void onItemClick(int idx) {
                JLog.i("onItemClick");
                switch (idx) {
                    case BottomBar.FEED://feed
                        initHome();
                        break;
                    case BottomBar.MAP://map
                        break;
                    case BottomBar.MESSAGE://msg
                        initChatList();
                        break;
                    case BottomBar.ME://me
                        initMy();
                        break;
                }
            }

            @Override
            public void onAddClick() {

            }
        });
    }

    private void selectPhoto() {
        Intent getImage = new Intent(this, MultiImageSelectorActivity.class);
        getImage.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
        getImage.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
        getImage.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        getImage.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST,
                new ArrayList<String>());
        startActivityForResult(getImage, StaticInApp.LOCAL_IMAGE);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        initClearCache();
    }

    /**
     * 对消息界面和我的界面进行设置消息提醒的红点
     */
//    private void setUnReadUi(ModelNotification mdNotification) {
//        if (mdNotification.checkValid()) {
//            //设置新增粉丝数
//            int follower = mdNotification.getFollower() > 99 ? 99 : mdNotification.getFollower();
//            badgeMy.setBadgeCount(follower);
//            if (fg_my != null) {
//                fg_my.setUnReadUi(mdNotification);
//            }
//            //设置点赞、评论新消息，提到我的，系统消息
//            int newMsg = mdNotification.getComment() + mdNotification.getDigg() + mdNotification.getAtme() + mdNotification.getUnread_system_message();
//            if (fg_message != null)
//                fg_message.setUnreadNotice(mdNotification);
//            int totalMsg = newMsg + unreadMsg;
//            badgeMessage.setBadgeCount(totalMsg > 99 ? 99 : totalMsg);
//        }
//    }


    // 如果首页数据页面没有被初始化过，则先执行初始话
    public void initHome() {
        if (fg_home == null) {
            fg_home = new FragmentHome();
        }

        currentFragment = fg_home;
        fragmentManager.beginTransaction().replace(R.id.home_ll_container, fg_home).addToBackStack(null)
                .commitAllowingStateLoss();
    }

    @Override
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
        if (intent.hasExtra("weiboId")) {
            int weiboId = intent.getIntExtra("weiboId", -1);
            // currentFragment.updataWeiboList(weiboId);
        }
        if (intent.hasExtra("type") && "createSuccess".equals(intent.getStringExtra("type"))) {
            int weiboId = intent.getIntExtra("weiboId", -1);
            // currentFragment.updataWeiboList(weiboId);
        }

        if (intent.hasExtra("type")) {
            skip_from = intent.getStringExtra("type");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (BuildConfig.DEBUG) {
        // 开启消息红点提醒，暂时关闭，因为开发影响log
//        Thinksns app = (Thinksns) getApplication();
//        app.startService();TODO linsr 2017年11月11日16:15:23 获取未读消息，小红点会报错，先屏蔽
//        }
        if (currentFragment != null && currentFragment.getAdapter() != null)
            currentFragment.getAdapter().notifyDataSetChanged();

        if (!TextUtils.isEmpty(skip_from)) {
            //切换至消息页面
            if (skip_from.equals("message")) {
                mBottomBar.setItemStatus(BottomBar.MESSAGE);
                skip_from = null;
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        Thinksns app = (Thinksns) getApplication();
        app.stopService();
    }

    @Override
    public String getTitleCenter() {
        return null;
    }

    @Override
    protected CustomTitle setCustomTitle() {

        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    public void refreshHeader() {

        if (mBottomBar.getCurrentIndex() == BottomBar.MESSAGE) {
        } else {
            if (currentFragment != null && currentFragment.getAdapter() != null)
                currentFragment.getAdapter().doRefreshHeader();
        }
    }

    @Override
    public void refreshFooter() {
        if (mBottomBar.getCurrentIndex() == BottomBar.MESSAGE) {
        } else {
            currentFragment.getAdapter().doRefreshFooter();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return mDoubleClickExit.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 清除消息未读提醒
     *
     * @param type   未读消息类型
     * @param unread 待清除的个数
     */
    @Override
    public void clearUnreadMessage(int type, int unread) {
//        switch (type) {
//            case StaticInApp.UNREAD_COMMENT:
//            case StaticInApp.UNREAD_DIGG:
//            case StaticInApp.UNREAD_AT:
//            case StaticInApp.UNREAD_SYSTEM:
//                int msg = badgeMessage.getBadgeCount();
//                msg = msg - unread;
//                if (msg <= 0)
//                    msg = 0;
//                badgeMessage.setBadgeCount(msg);
//                break;
//            case StaticInApp.UNREAD_FOLLOW:
//                badgeMy.setBadgeCount(0);
//                break;
//        }
    }

    private class ActivityHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.arg1 == SELECT) {
                return;
            } else if (GET_SOCKET_ADDRESS == msg.arg1) {
                String socketAddress = String.valueOf(msg.obj);
                if (!TextUtils.isEmpty(socketAddress) && !"null".equals(socketAddress)) {
                    PrefUtils.saveSocketAddress(ActivityHome.this, socketAddress);
                }
                //启动socket连接
                TSChatManager.login(Thinksns.getMy());
            }
        }
    }

    @Override
    protected void onDestroy() {
        Thinksns.getApplication().stopService();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        this.finish();
    }

    /**
     * 初始化我家页面
     */
    public void initMy() {
        if (fg_my == null) {
            fg_my = new FragmentMy();
        }
        currentFragment = fg_my;
        fragmentManager.beginTransaction().replace(R.id.home_ll_container, fg_my).addToBackStack(null).commit();
    }

    /**
     * 初始化消息页面
     */
    public void initChatList() {
        if (fg_message == null) {
            fg_message = FragmentMessage.newInstance(mdNotification);
        }
        currentFragment = fg_message;
        fragmentManager.beginTransaction().replace(R.id.home_ll_container, fg_message).addToBackStack(null).commit();
    }


    @Override
    public void update(int count) {

        unreadMsg += count;
        //TODO 处理未读消息
        Log.e("AndroidHome", "unread msg count:" + unreadMsg);
        if (unreadMsg <= 0) {
            unreadMsg = 0;
        } else {
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 刷新首页数据
        if (resultCode == RESULT_OK) {
            Intent intent = null;
            switch (requestCode) {
                case StaticInApp.LOCAL_IMAGE:
                    List<String> photoList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    boolean original = data.getBooleanExtra(MultiImageSelectorActivity.EXTRA_SELECT_ORIGIANL, false);
                    if (Bimp.address.size() < 9) {
                        for (String addr : photoList) {
                            if (!Bimp.address.contains(addr)) {
                                Bimp.address.add(addr);
                            }
                        }
                    }
                    //跳转至发布微博页
//                    intent = new Intent(ActivityHome.this, ActivityCreateBase.class);
//                    intent.putExtra("type", AppConstant.CREATE_ALBUM_WEIBO);
//                    intent.putExtra("is_original", original);
//                    startActivity(intent);
                    Anim.in(ActivityHome.this);
                    break;
                case StaticInApp.CAMERA_IMAGE:
                    if (Bimp.address.size() < 9) {
                        Bimp.address.add(listener_selectImage.getImagePath());
                    }
                    //跳转至发布微博页
//                    intent = new Intent(ActivityHome.this, ActivityCreateBase.class);
//                    intent.putExtra("type", AppConstant.CREATE_ALBUM_WEIBO);
//                    intent.putExtra("is_original", false);
//                    startActivity(intent);
                    Anim.in(ActivityHome.this);
                    break;
                case AppConstant.CREATE_VIDEO_WEIBO:
//                    intent = new Intent(ActivityHome.this, ActivityCreateBase.class);
//                    intent.putExtra("type", AppConstant.CREATE_VIDEO_WEIBO);
//                    startActivity(intent);
                    Anim.in(ActivityHome.this);
                    break;
                default:
                    if (currentFragment instanceof FragmentHome) {
                        currentFragment.onActivityResult(requestCode, resultCode, data);
                    }
                    if (currentFragment instanceof FragmentMy) {
                        ((FragmentMy) currentFragment).showBasicInfo(Thinksns.getMy());
                    }
            }
        }

    }

    /**
     * 动态获取聊天 Socket 地址
     */
    private void getSocketAddress() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = "";
                try {
                    result = new Api.Message().getSocketAddress();
                } catch (ApiException e) {
                    e.printStackTrace();
                } finally {
                    Message msg = handler.obtainMessage();
                    msg.obj = result;
                    msg.arg1 = GET_SOCKET_ADDRESS;
                    handler.sendMessage(msg);
                }
            }
        }).start();

    }

    /**
     * 本地没有更新 socket 地址时，刷新聊天界面触发
     *
     * @param type
     */
    @Subscribe
    public void refreshSocketAddress(int type) {
        if (GET_SOCKET_ADDRESS == type) {
            getSocketAddress();
        }
    }

    /*根据隐私设置自动清空缓存判断是否清缓存*/
    private void initClearCache() {
        int checkedId = PreferenceUtils.getAutoClearCacheId();
        if (checkedId == 0 || checkedId == R.id.rb_never) {
            return;
        }
        long lastClearTime = PreferenceUtils.getLastClearTime();
        long currentTime = System.currentTimeMillis();
        long time = (currentTime - lastClearTime) / (1000 * 60);
        double day = time / (24 * 60);
        if (checkedId == R.id.rb_day) {
            if (day >= 1) {
                clearCache();
            }
        } else if (checkedId == R.id.rb_week) {
            if (day >= 7) {
                clearCache();
            }
        } else if (checkedId == R.id.rb_month) {
            if (day >= 30) {
                clearCache();
            }
        }
    }

    private void clearCache() {
        UnitSociax unit = new UnitSociax(this);
        unit.clearAppCache();
    }

}
